import React from 'react';
import { inject, observer } from 'mobx-react';
import { WeaTableNew } from 'comsMobx';

const WeaTable = WeaTableNew.WeaTable;
import allStores from '../stores/index';

import LeftOrgTree from './carUseView/LeftOrgTree';
import NoRight from './NoRight';
import {
  WeaTop,
  WeaTab,
  WeaLeftTree,
  WeaLeftRightLayout,
  WeaSearchGroup,
  WeaRightMenu,
  WeaLocaleProvider,
  WeaErrorPage,
  WeaTools,
} from 'ecCom';
import {
  Button, Form, Modal, Spin,
}
  from 'antd';
import Immutable from 'immutable';
import CarConstant from '../util/CarConstant';
import * as CarUtil from '../util/CarUtil';
import CarViewDialog from './car/dialog/CarViewDialog';
import CarInfoDialog from './car/dialog/CarInfoDialog';

const getLabel = WeaLocaleProvider.getLabel;
const confirm = Modal.confirm;
const is = Immutable.is;
const createForm = Form.create;
const FormItem = Form.Item;
let currSubCompany = 0;
let currSubCompanyname = '';

/**
 * 车辆查询
 */
@inject('carManagerStore')
@observer
class CarManager extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      carsdetachable: 0,
      isRight: 2,
      subCompanyId: 0,
      subCompanyName: '',
      carstatus: 'carlist',
    };
  }

  componentWillMount() {
    const { carManagerStore } = this.props;
    carManagerStore.getCarDetachable(this.setCarDetachable); // 获取分权信息
  }

	setCarDetachable = (result) => {
	  if (result) {
	    this.setState({
	      carsdetachable: result.detachable && result.detachable == 1 ? 1 : 0,
	      isRight: result.isRight == 1 ? 1 : 0,
	    });
	  }
	}

	componentDidMount() {
	  const { carManagerStore } = this.props;
	  carManagerStore.doTableLoading(); // 初始化列表
	  carManagerStore.initConditionDatas(); // 初始化高级搜索区域
	}

	componentWillReceiveProps(nextProps) {
	}

	componentWillUnmount() {
	  // 组件卸载时一般清理一些状态
	  const { carManagerStore } = this.props;

	  carManagerStore.setShowSearchAd(false);
	  carManagerStore.setSelectedKey('all');
	  carManagerStore.clearFormFields();
	}


	render() {
	  const { carManagerStore } = this.props;
	  const { loading, form, conditioninfo, selectedKey, showSearchAd, sessionkey, tableStore } = carManagerStore;
	  const { carsdetachable, isRight, subCompanyId, subCompanyName } = this.state;
	  const table = () => (<div className="wea-right-container">
  <WeaTab
  ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@varoe0`}
  datas={this.getTobTab()}
  keyParam="groupid"
	      onChange={this.changeTab.bind(this)}
  selectedKey={selectedKey}
  searchType={['base', 'advanced']}
	      searchsBaseValue={form.isFormInit && form.getFormParams() && form.getFormParams().carNo}
	      setShowSearchAd={(bool) => { carManagerStore.setShowSearchAd(bool); }}
  showSearchAd={showSearchAd}
  hideSearchAd={() => { carManagerStore.setShowSearchAd(false); }}
	      searchsAd={CarUtil.getSearchs(form, conditioninfo, this.refreshAd)}
	      buttonsAd={this.getTabButtonsAd()}
  onSearch={(v) => { carManagerStore.doTableLoading(); }}
  onSearchChange={(v) => { carManagerStore.appendFormFields({ carNo: v }); }}
	    />

  <WeaTable
	      ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@bvzfwz`}
  loading={loading}
	      sessionkey={sessionkey}
	      comsWeaTableStore={tableStore}
  hasOrder
  needScroll
	      getColumns={this.getNewColumns}
	      onOperatesClick={this.onOperatesClick.bind(this)}
	    />
	  </div>);

	  return (
  <div className="wea-car-mine">
  <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@l3i8m8`} spinning={loading} >
      {
	          isRight == 2 ?
	            (
  <div style={{ height: '600px', width: '100%' }} />
	            )
	            :
	            (
	              isRight == 1 ?
	                (<WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@9pepio`} datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}>
	                  <WeaTop
	                    ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@jqnewg`}
    title={getLabel(19021, '车辆信息维护')}
    loading={loading}
    icon={CarConstant.icon}
	                    iconBgcolor={CarConstant.iconBgColor}
	                    buttonSpace={10}
	                    showDropIcon
	                    dropMenuDatas={this.getRightMenu()}
	                    onDropMenuClick={this.onRightMenuClick.bind(this)}
	                    buttons={[
	                      carManagerStore.operatelevel > 0 ?
	                        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@6bii09@add`} type="primary" onClick={this.add}>{getLabel(20317, '新建车辆')}</Button>
	                        : null,
	                    ]}
  >
	                    {
	                      carsdetachable === 1 ?
	                        (
	                          <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@kq9711`} defaultShowLeft={false} leftCom={<LeftOrgTree ecId={`${this && this.props && this.props.ecId || ''}_LeftOrgTree@laetp9`} changeSubcompany={this.changeSubcompany.bind(this)} />} >
    {table()}
  </WeaLeftRightLayout>
	                        ) : (
	                          table()
	                        )
	                    }
  </WeaTop>
	                </WeaRightMenu>
	                )
	                :
	                (<NoRight ecId={`${this && this.props && this.props.ecId || ''}_NoRight@ru4lag`} visible={isRight != 1} />)
	            )
	        }
    </Spin>

	      <CarViewDialog ecId={`${this && this.props && this.props.ecId || ''}_CarViewDialog@cm6kju`} ref="carview" />
	      <CarInfoDialog ecId={`${this && this.props && this.props.ecId || ''}_CarInfoDialog@by9szp`} ref="info" reloadTableList={this.reloadTableList.bind(this)} />
	    </div>
	  );
	}


	getTobTab = () => [
	  { groupid: 'carlist', title: getLabel('387926', '未封存车辆'), viewcondition: 0 },
	  { groupid: 'depositlist', title: getLabel(387486, '已封存车辆'), viewcondition: 1 },
	]
	// 右侧操作按钮
	onOperatesClick = (record, index, operate, flag) => {
	  if (flag === '0') {
	    this.editcar(record.id, 0);
	  } else if (flag === '1') {
	    const carNo = record.carNo;
	    const { carManagerStore } = this.props;
	    const managerObj = this;
	    Modal.confirm({
	      title: `${getLabel(385848, '确认要删除车辆')}[${carNo}]？`,
	      onOk() {
	        carManagerStore.delCarinfo({ id: record.id }, managerObj.reloadTableList.bind(managerObj));
	      },
	      onCancel() { },
	    });
	  } else if (flag === '2' || flag === '3') {
	    const carNo = record.carNo;
	    const deposit = record.deposit;
	    const { carManagerStore } = this.props;
	    const managerObj = this;
	    Modal.confirm({
	      title: record.deposit === '1' ? `${getLabel(385849, '确认要解封车辆')}[${carNo}]？` : `${getLabel(385850, '确认要封存车辆')}[${carNo}]？`,
	      onOk() {
	        carManagerStore.depositCar({ id: record.id, deposit: record.deposit }, managerObj.reloadTableList.bind(managerObj));
	      },
	      onCancel() { },
	    });
	  } else if (flag === '4') { // 共享范围
	    this.editcar(record.id, 1);
	  }
	}


	// 新建
	add = () => {
	  const { carManagerStore } = this.props;
	  carManagerStore.setState({ createOrEdit: 0, showCreate: true });
	  const data = this.state;
	  data.subCompanyId = currSubCompany;
	  data.subCompanyName = currSubCompanyname;
	  this.refs.info.wrappedInstance.open(data);
	}

	// 查看
	carview = (id) => {
	  this.refs.carview.wrappedInstance.open(id);
	}

	// 编辑
	editcar = (id, tabid) => {
	  const { carManagerStore } = this.props;
	  carManagerStore.getShareList({ id, preview: 0 });
	  carManagerStore.setState({
	    createOrEdit: 1,
	    editSelKey: tabid,
	    showCreate: true,
	    selectId: id,
	  });
	  this.refs.info.wrappedInstance.loadEdit(id);
	}

	// 重新加载列表
	reloadTableList() {
	  const { carManagerStore } = this.props;
	  carManagerStore.setShowSearchAd(false);
	  carManagerStore.reloadTable();
	}

	changeSubcompany = (nodeObj) => {
	  let id = '';
	  let name = '';
	  if (nodeObj && nodeObj.id && nodeObj.id > 0) {
	    id = nodeObj.id;
	    name = nodeObj.name;
	  }
	  currSubCompany = id;
	  currSubCompanyname = name;
	  // this.setState({subCompanyId:nodeObj.id,subCompanyName:nodeObj.name});
	  const { carManagerStore } = this.props;
	  carManagerStore.clearFormFields();
	  carManagerStore.setFormFields({
	    subCompanyId: {
	      value: id,
	      valueSpan: name,
	      valueObj: [
	        {
	          id,
	          name,
	        },
	      ],
	    },
	  });
	  carManagerStore.setShowSearchAd(false);
	  carManagerStore.doTableLoading();
	}


	// 切换tab事件
	changeTab(theKey) {
	  const { carManagerStore } = this.props;
	  this.setState({ carstatus: theKey });
	  carManagerStore.setSelectedKey(theKey);
	  carManagerStore.setShowSearchAd(false);
	  carManagerStore.clearFormFields();
	  carManagerStore.setFormFields({
	    subCompanyId: {
	      value: currSubCompany,
	      valueObj: [
	        {
	          id: currSubCompany,
	        },
	      ],
	    },
	  });
	  carManagerStore.doTableLoading();
	}

	// 右键菜单
	getRightMenu() {
	  const btns = [];
	  const { carManagerStore } = this.props;
	  if (carManagerStore.operatelevel > 0) {
	    btns.push({ key: 'add', icon: <i className="icon-coms-New-Flow" />, content: getLabel(20317, '新建车辆') });
	  }
	  return btns;
	}

	// 右键菜单事件绑定
	onRightMenuClick(key) {
	  if (key == 'add') {
	    this.add();
	  }
	}

	// 高级搜索底部按钮定义
	getTabButtonsAd() {
	  const { carManagerStore } = this.props;
	  return [
	    (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@pyuqck@refreshAd`} type="primary" onClick={() => { this.refreshAd(); }}>{getLabel(197, '搜索')}</Button>),
	    (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@58vetz@$reset`} type="ghost" onClick={() => { carManagerStore.clearFormFields(); }}>{getLabel(2022, '重置')}</Button>),
	    (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@nent3i@cancel`} type="ghost" onClick={() => { carManagerStore.setShowSearchAd(false); }}>{getLabel(201, '取消')}</Button>),
	  ];
	}

	refreshAd = () => {
	  const { carManagerStore } = this.props;
	  carManagerStore.setShowSearchAd(false);
	  carManagerStore.doTableLoading();
	}

	// 自定义过滤渲染
	getNewColumns = (columns) => {
	  let newColumns = '';
	  newColumns = columns.map((column) => {
	    const newColumn = column;
	    newColumn.render = (text, record, index) => { // 前端元素转义
	      const valueSpan = record[`${newColumn.dataIndex}span`] !== undefined ? record[`${newColumn.dataIndex}span`] : record[newColumn.dataIndex];
	      if (newColumn.dataIndex == 'carNo') {
	        return <div className="wea-url-name" style={{ cursor: 'pointer' }} title={text} onClick={() => { this.carview(record.randomFieldId); }} dangerouslySetInnerHTML={{ __html: valueSpan }} />;
	      }
	      return <div className="wea-url" dangerouslySetInnerHTML={{ __html: valueSpan }} />;
	    };
	    return newColumn;
	  });
	  return columns;
	}
}


export default WeaTools.tryCatch(React,
  props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@fjl3mp`} msg={props.error ? props.error : '对不起，该页面异常，请联系管理员！'} />,
  { error: '' },
)(CarManager);
